package com.whj.wkpt.validator;

import com.whj.wkpt.entity.Task;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import java.math.BigDecimal;

@Component
public class TaskValidator implements Validator {

    @Override
    public boolean supports(Class<?> clazz) {
        return Task.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        Task task = (Task) target;

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "title", "title.empty", "任务标题不能为空");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "description", "description.empty", "任务描述不能为空");

        if (task.getBudget() == null) {
            errors.rejectValue("budget", "budget.empty", "任务预算不能为空");
        } else if (task.getBudget().compareTo(BigDecimal.ZERO) <= 0) {
            errors.rejectValue("budget", "budget.negative", "任务预算必须大于0");
        } else if (task.getBudget().compareTo(new BigDecimal("999999.99")) > 0) {
            errors.rejectValue("budget", "budget.tooLarge", "任务预算不能超过999999.99");
        }

        if (task.getTitle() != null && task.getTitle().length() > 200) {
            errors.rejectValue("title", "title.tooLong", "任务标题不能超过200个字符");
        }
    }
}